<template>
  <a-table
    :expandedKeys="expandedKeys"
    :expandable="expandable"
    :data="table.dataList"
    v-bind="table"
    @expand="expand"
    :bordered="{ wrapper: true, cell: true }"
    :pagination="false"
    :loading="table.tableLoading"
  >
    <template #columns>
      <tableColumn :columns="columns">
        <template v-for="(_, slotName) in slots" #[slotName]="slotData" :key="slotName">
          <slot :name="slotName" v-bind="{ ...slotData, tableIndex: 1 }"></slot>
        </template>
      </tableColumn>
    </template>
    <template #expand-icon="{ expanded, record }">
      <div class="arco-table-expand-btn" :class="{ 'arco-icon-disabled': !record.orgInfoList || record.orgInfoList.length == 0 }">
        <icon-plus v-if="!expanded" />
        <icon-minus v-else />
      </div>
    </template>
    <template #expand-row="{ record }">
      <div style="margin: 20px">
        <a-table
          :data="record.orgInfoList"
          :loading="expandTable.tableLoading"
          :pagination="false"
          :bordered="{ wrapper: true, cell: true }"
        >
          <template #columns>
            <tableColumn :columns="expandColumns">
              <template v-for="(_, slotName) in slots" #[slotName]="slotData" :key="slotName">
                <slot :name="slotName" v-bind="{ ...slotData, tableIndex: 2 }"></slot>
              </template>
            </tableColumn>
          </template>
        </a-table>
      </div>
    </template>
  </a-table>
  <table-footer v-if="table.pagination" :pagination="table.pagination" :showRefresh="false" position="end" @change="pagenationChangeFn" />
</template>
<script setup>
  import tableColumn from './table-column.vue'

  import { computed, ref, useSlots, watch } from 'vue'
  import { isEqual } from 'lodash-es'

  const props = defineProps({
    table: {
      type: Object,
      default: () => {},
    },
    expandTable: {
      type: Object,
      default: () => {},
    },
  })

  const slots = useSlots()
  const emit = defineEmits(['expand', 'loadData', 'pagenationChange', 'foldClick', 'update:tableIsFold', 'update:tableIsTableHeaderFold'])

  const isFold = ref(true)
  const isTableHeaderFold = ref(true)
  const columns = computed(() => (props.table?.columns ? props.table.columns : []))
  const expandColumns = computed(() => (props.expandTable?.columns ? props.expandTable.columns : []))

  // 展开
  const expandable = {
    title: '',
    width: 50,
  }
  const expandedKeys = ref([])
  const expand = (rowKey, record) => {
    if (!record.orgInfoList || record.orgInfoList.length == 0) {
      return
    }

    let expandId = +rowKey
    if (expandedKeys.value.indexOf(expandId) == -1) {
      expandedKeys.value.push(expandId)
    } else {
      expandedKeys.value.splice(expandedKeys.value.indexOf(expandId), 1)
    }
  }

  const pagenationChangeFn = () => {
    emit('loadData')
    emit('pagenationChange')
  }

  // 递归循环收起
  const loopFold = (columns) => {
    columns.forEach((item) => {
      if (item.isToggle != undefined) {
        item.toggleStatus = false
      }
      if (item.isChildShow != undefined) {
        item.isChildShow = true
      }
      if (item.children && item.children.length > 0) {
        loopFold(item.children)
      }
    })
  }

  // 递归循环展开
  const loopExpand = (columns) => {
    columns.forEach((item) => {
      if (item.isToggle != undefined) {
        item.toggleStatus = true
      }
      if (item.isChildShow != undefined) {
        item.isChildShow = false
      }
      if (item.children && item.children.length > 0) {
        loopExpand(item.children)
      }
    })
  }

  // 表头一键展开/收起
  const handleTableHeaderFoldClick = () => {
    isTableHeaderFold.value = !isTableHeaderFold.value

    if (!isTableHeaderFold.value) {
      loopExpand(columns.value)
      loopExpand(expandColumns.value)
    } else {
      loopFold(columns.value)
      loopFold(expandColumns.value)
    }

    emit('update:tableIsTableHeaderFold', isTableHeaderFold.value)
  }

  const handleFoldClick = () => {
    isFold.value = !isFold.value

    if (!isFold.value) {
      expandedKeys.value = props.table.dataList.map((item) => {
        if (item.orgInfoList && item.orgInfoList.length > 0) {
          return item.key
        }
      })
    } else {
      expandedKeys.value = []
    }

    emit('update:tableIsFold', isFold.value)
  }

  watch(
    () => props.table.dataList,
    (newVal, oldVal) => {
      console.log('table.dataList', newVal, oldVal)

      if (newVal && newVal.length > 0) {
        // 已经是一键展开状态
        if (!isFold.value) {
          expandedKeys.value = newVal.map((item) => {
            if (item.orgInfoList && item.orgInfoList.length > 0) {
              return item.key
            }
          })
        } else if (isFold.value && !isEqual(newVal, oldVal)) {
          expandedKeys.value = []
        }

        // 表头已经是展开状态
        if (!isTableHeaderFold.value) {
          loopExpand(columns.value)
          loopExpand(expandColumns.value)
        }
      }
    },
    {
      deep: true,
    }
  )

  defineExpose({
    handleFoldClick,
    handleTableHeaderFoldClick,
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-expand-btn:hover) {
    color: var(--color-text-4);
    background-color: var(--color-secondary-disabled);
    border: 1px solid transparent;
  }

  :deep(.arco-table-tr-expand) {
    .arco-table-td {
      &:hover {
        .arco-table-td.arco-table-col-fixed-right::before,
        .arco-table-td.arco-table-col-fixed-left::before {
          background-color: #fff !important;
        }
      }
    }

    .arco-table {
      border: 1px solid #e5e6eb;
      border-bottom: none;
      border-right: none;

      .arco-table-th {
        background-color: var(--color-fill-1);
      }

      .arco-table-td {
        background-color: #fff !important;
      }
    }
  }

  .arco-icon-disabled {
    color: var(--color-text-4);
    background-color: var(--color-secondary-disabled);
    border: 1px solid transparent;
    cursor: not-allowed;
  }
</style>
